package red.yancloud.www.ui.activity

import android.app.Activity
import android.content.Intent
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.webkit.JavascriptInterface
import androidx.appcompat.widget.AppCompatTextView
import com.alibaba.fastjson.JSONObject
import com.example.zhouwei.library.CustomPopWindow
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_book_info.*
import kotlinx.android.synthetic.main.activity_book_info.back_iv
import kotlinx.android.synthetic.main.activity_book_info.webViewActivity_refreshLayout
import kotlinx.android.synthetic.main.activity_news_info.*
import okhttp3.ResponseBody
import org.greenrobot.eventbus.EventBus
import red.yancloud.www.R
import red.yancloud.www.base.BaseWebViewActivity
import red.yancloud.www.common.Constants
import red.yancloud.www.common.MessageEvent
import red.yancloud.www.db.sharedpreference.UserInfoShardPreference
import red.yancloud.www.internet.api.RedCloudApis
import red.yancloud.www.internet.bean.FavoriteState
import red.yancloud.www.util.NetworkUtils
import red.yancloud.www.util.ToastUtils
import red.yancloud.www.util.UrlUtils

/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/7/26 9:53
 * E_Mail：yh131412hys@163.com
 * Describe：新闻详情
 * Change：
 * @Version：V1.0
 */
class NewsInfoActivity : BaseWebViewActivity() {

    private val TAG = "NewsInfoActivity"

    private var model:String = ""
    private var modelId:String = ""
    private var collectId:String = ""
    private var state: Int = -1
    private var currentState: Int = -1

    override val layoutId: Int
        get() = R.layout.activity_news_info

    override fun initData() {
        super.initData()

        model = intent.getStringExtra("model")
        modelId = intent.getStringExtra("id")
    }

    override fun configViews() {
        super.configViews()

//        zhiku-----http://www.yancloud.red/Yancloudapp/News/entry/id/1904.html 知库词条 http://zhi.yancloud.red/index.php?r=entry/entry/view&id=1232
//        zhiku-----http://www.yancloud.red/Yancloudapp/News/mjentry/id/51.html 知库-专家团队 http://zhi.yancloud.red/index.php?r=account/advisor/view&id=47
// 知库-作者团队 http://zhi.yancloud.red/index.php?r=author/view&id=186

//        news-----http://www.yancloud.red/Yancloudapp/News/index/id/11840.html
//        painting-----http://www.yancloud.red/Yancloudapp/Article/manhuiindex/id/12371.html
//        travel-----http://www.yancloud.red/Yancloudapp/News/index?id=10954
//        really-----http://www.yancloud.red/Yancloudapp/News/index?id=12363
//        redsbag-----http://www.yancloud.red/Yancloudapp/News/index?id=3028
//        subject-----http://www.yancloud.red/Yancloudapp/News/index?id=2604
        Log.d(TAG,"$model-----$mUrl")

        back_iv.setOnClickListener(this)
        newInfoActivity_more_iv.setOnClickListener(this)

        webViewActivity_refreshLayout.setEnableLoadMore(false)

//        首页漫绘延安 http://www.yancloud.red/Yancloudapp/Index/manhui.html
        if (model == Constants.CollectModel.ZHIKUMJ
            || mUrl.contains("/Yancloudapp/Index/manhui.html")
            || model == "banner") {

            newInfoActivity_more_iv.visibility = View.INVISIBLE
        }
    }

    override fun addJavaScriptInterface() {

        mWebView.addJavascriptInterface(object : Any() {

            @JavascriptInterface
            fun loadData(){
                mHandler.post(object :Runnable{
                    override fun run() {
                        mWebView.loadUrl("javascript:waves(" + UrlUtils.makeJsonText() + ")")
                        if (!(mContext as Activity).isFinishing) {
                            loadingDialog.dismiss()
                        }
                    }
                })
            }

            @JavascriptInterface
            fun gotourl(url: String,model: String,id: String) {
                mHandler.post {

                    startActivity(
                        Intent(mContext, NewsInfoActivity::class.java)
                            .putExtra("url", Constants.BASE_RED_CLOUD_HOST_URL+url)
                            .putExtra("model",model)
                            .putExtra("id",id)
                    )
                }
            }

            /**
             * vkey：指定大页面
             * vtoclas：区分小分类
             */
            @JavascriptInterface
            fun gotopage(key: String,value: String) {

                mHandler.post {

                    Log.d(TAG,"gotopage:$key==$value")
                    if (key=="manhui"){

                        startActivity(Intent(mContext,DiffuseYanAnActivity::class.java).putExtra("id",value))
                    }
                }
            }
        },"demo")
    }

    public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.back_iv-> finish()
            R.id.newInfoActivity_more_iv-> {

                if (!NetworkUtils.isConnected(mContext)) {
                    ToastUtils.toastNetErrorMsg()
                    return
                }

                if (UserInfoShardPreference.instance.isLogin) {

                    RedCloudApis.getInstance().getFavoriteState(UserInfoShardPreference.instance.uid,modelId,model,object :
                        Observer<FavoriteState> {
                        override fun onComplete() {
                        }

                        override fun onSubscribe(d: Disposable) {
                        }

                        override fun onNext(t: FavoriteState) {

                            if (t.code == Constants.SYSTEM_OK) {

                                if (t.data != null) {

                                    collectId = t.data.id
                                    state = Constants.CollectType.COLLECT
                                }else{

                                    state = Constants.CollectType.NOT_COLLECT
                                }

                                currentState = state

                                initPopupWindow(v)
                            }
                        }

                        override fun onError(e: Throwable) {

                            state = Constants.CollectType.NOT_COLLECT
                            currentState = state
                            initPopupWindow(v)
                        }
                    })
                }else{

                    state = Constants.CollectType.NOT_COLLECT
                    currentState = state
                    initPopupWindow(v)
                }
            }
        }
    }

    private fun initPopupWindow(v: View?) {

        val contentView = LayoutInflater.from(this@NewsInfoActivity).inflate(R.layout.news_info_popup_window_layout, null)
        //创建并显示popWindow -360
        val mCustomPopWindow = CustomPopWindow.PopupWindowBuilder(this@NewsInfoActivity)
            .setView(contentView)
            .create()
            .showAsDropDown(v, -20, -40)

        contentView.findViewById<AppCompatTextView>(R.id.share_tv).setOnClickListener {

            if (model == Constants.CollectModel.ZHIKU) {

                //        zhiku-----http://www.yancloud.red/Yancloudapp/News/entry/id/1904.html 知库词条 http://zhi.yancloud.red/index.php?r=entry/entry/view&id=1232
//        zhiku-----http://www.yancloud.red/Yancloudapp/News/mjentry/id/51.html 知库-专家团队 http://zhi.yancloud.red/index.php?r=account/advisor/view&id=47
// 知库-作者团队 http://zhi.yancloud.red/index.php?r=author/view&id=186
                if (mUrl.contains("entry")) {

                    mUrl = "http://zhi.yancloud.red/index.php?r=entry/entry/view&id=$modelId"
                }else if (mUrl.contains("mjentry")){

                    mUrl = "http://zhi.yancloud.red/index.php?r=account/advisor/view&id=$modelId"
                }
            }else if (model == Constants.CollectModel.PAINTING){

                //        painting-----http://www.yancloud.red/Yancloudapp/Article/manhuiindex/id/12371.html
                mUrl = "http://www.yancloud.red/Painting/Index/detail/?id=$modelId"
            }else if (model == Constants.CollectModel.TRAVEL){

                //        travel-----http://www.yancloud.red/Yancloudapp/News/index?id=10954
                mUrl = "http://www.yancloud.red/Travel/Index/formerHome/t/red/?id=$modelId"
            }else if (model == Constants.CollectModel.REALLY){

                //        really-----http://www.yancloud.red/Yancloudapp/News/index?id=12363
                mUrl = "http://www.yancloud.red/Really/really_info.html?id=$modelId"
            }else if (model == Constants.CollectModel.REDSBAG){

                //        redsbag-----http://www.yancloud.red/Yancloudapp/News/index?id=3028
                mUrl = "http://www.yancloud.red/Redsbag/Redsbag_info.html?id=$modelId"
            }else if (model == Constants.CollectModel.SUBJECT){

                // 红云专题       subject-----http://www.yancloud.red/Yancloudapp/News/index?id=2604
                mUrl = "http://www.yancloud.red/Subject/Special/info/?id=$modelId"
            }

            val image = UMImage(this, R.mipmap.ic_launcher)
            val web = UMWeb(mUrl) //切记切记 这里分享的链接必须是http开头
            web.title = mWebView.title//标题
            web.setThumb(image)  //缩略图
            web.description = "你要分享内容的描述"//描述

            ShareAction(this)/*.withText(mWebView.title)*/.withMedia(image).withMedia(web)
                /*WEIXIN,
WEIXIN_CIRCLE,微信朋友圈
WEIXIN_FAVORITE, 微信收藏
TENCENT, 腾讯微博*/
                .setDisplayList(SHARE_MEDIA.SINA,
                    SHARE_MEDIA.QQ,SHARE_MEDIA.QZONE,
                    SHARE_MEDIA.WEIXIN,SHARE_MEDIA.WEIXIN_CIRCLE,
                    SHARE_MEDIA.MORE)
                .setCallback(umShareListener).open()
            mCustomPopWindow.dissmiss()
        }
//                ShareAction(this).withSubject(mWebView.title).withText("hello").withMedia(
//                    UMImage(this,R.mipmap.ic_launcher)
//                ).setDisplayList(SHARE_MEDIA.MORE)
//                    .setCallback(umShareListener).open();

        val collectTv = contentView.findViewById<AppCompatTextView>(R.id.collect_tv)
        if (state == Constants.CollectType.COLLECT) {

            val drawable = resources.getDrawable(R.mipmap.news_collect_ic)
            // 这一步必须要做,否则不会显示.
            drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
            collectTv.setCompoundDrawables(drawable, null, null, null)
        }

        collectTv.setOnClickListener {

            if (UserInfoShardPreference.instance.isLogin) {

                if (state == Constants.CollectType.COLLECT) {

                    RedCloudApis.getInstance().myCollectDelete(UserInfoShardPreference.instance.uid,collectId,object : Observer<ResponseBody> {
                        override fun onComplete() {
                        }

                        override fun onSubscribe(d: Disposable) {
                        }

                        override fun onNext(t: ResponseBody) {

                            val result = String(t.bytes())

                            if (!TextUtils.isEmpty(result)) {

                                val jsonObject = JSONObject.parseObject(result)

                                if (jsonObject.getString("code") == Constants.SYSTEM_OK) {

                                    val drawable = resources.getDrawable(R.mipmap.news_not_collect_ic)
                                    // 这一步必须要做,否则不会显示.
                                    drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
                                    collectTv.setCompoundDrawables(drawable, null, null, null)

                                    ToastUtils.showToast(getString(R.string.cancel_collect))
                                    mCustomPopWindow.dissmiss()

                                    state = Constants.CollectType.NOT_COLLECT
                                }else{

                                    ToastUtils.showToast(jsonObject.getString("msg"))
                                }
                            }else{

                                ToastUtils.showToast(getString(R.string.cancel_collect_failure))
                            }
                        }

                        override fun onError(e: Throwable) {
                        }
                    })

                }else if(state == Constants.CollectType.NOT_COLLECT){

                    RedCloudApis.getInstance().addFavorite(UserInfoShardPreference.instance.uid,mWebView.title,modelId,model,object : Observer<ResponseBody> {
                        override fun onComplete() {
                        }

                        override fun onSubscribe(d: Disposable) {
                        }

                        override fun onNext(t: ResponseBody) {

                            val result = String(t.bytes())
                            if (!TextUtils.isEmpty(result)) {

                                val parseObject = JSONObject.parseObject(result)
                                if (parseObject.getString("code") == Constants.SYSTEM_OK) {

                                    val drawable = resources.getDrawable(R.mipmap.news_collect_ic)
                                    // 这一步必须要做,否则不会显示.
                                    drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
                                    collectTv.setCompoundDrawables(drawable, null, null, null)

                                    ToastUtils.showToast(getString(R.string.collect_success))
                                    state = Constants.CollectType.COLLECT
                                }else{

                                    ToastUtils.showToast(getString(R.string.collect_failure))
                                }

                                mCustomPopWindow.dissmiss()
                            }
                        }

                        override fun onError(e: Throwable) {

                            ToastUtils.showToast(getString(R.string.collect_failure))
                            mCustomPopWindow.dissmiss()
                        }
                    })
                }
                //                    collectTv.setText(R.string.already_collect)
            }else{

                ToastUtils.showToast(R.string.not_login_prompt)
                startActivity(Intent(this,LoginActivity::class.java))
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()

        Log.d(TAG,"$currentState-----onDestroy$state")
        if (currentState != state) {

            EventBus.getDefault().post(MessageEvent(Constants.REFRESH_MY_COLLECT,""))
        }
    }

    private val umShareListener = object : UMShareListener {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        override fun onStart(platform: SHARE_MEDIA) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        override fun onResult(platform: SHARE_MEDIA) {

            ToastUtils.showToast("分享成功了")
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        override fun onError(platform: SHARE_MEDIA, t: Throwable) {

            ToastUtils.showToast("分享失败" + t.message)
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        override fun onCancel(platform: SHARE_MEDIA) {

//            ToastUtils.showToast("取消了")
        }
    }
}
